<template>
  <div class="accessList">
    <!-- table -->
      <accessTable
        :isAdd="limitArr.indexOf('access_list_insert') > -1"
        :isShowPage="false"
        @addFun="addFun"
        @search="queryTableList"
        :quickSearchForm="quickSearchForm"
        :tableHeader="tableHeader"
        :tablePages="tablePages"
        :tableData="tableData">
      </accessTable>
    <!-- 抽屉 -->
      <drawer
        direction="rtl"
        :title="drawer.title"
        :drawer="drawer.isShow"
        @save="confirmFun"
        @cancelFun="cancelFun"
        @closeDraw="cancelFun">
        <template slot="column">
          <addOrEdit ref="accessInfo"></addOrEdit>
        </template>
      </drawer>
  </div>

</template>
<script lang='ts'>
import { Component, Vue, Ref } from 'vue-property-decorator'
import accessTable from '@/views/config/webchat/channel/base/accessTable.vue'
import drawer from '@/common/views/drawer/index.vue'
import addOrEdit from '@/views/config/webchat/globalSetting/agentStatus/addOrEdit.vue'
import { CommonModule } from '@/store/modules/common'
import { channelConfigMoudle } from '@/store/modules/config/channel/index'
import { deepClone } from '@/utils/common'
import { checkPermission } from '@/utils/directive'
// eslint-disable-next-line no-unused-vars
import { Form as ElForm } from 'element-ui'
interface InterStatus {
  [x: string]: any
  status: 'enable' | 'disable'
}
interface TableItem {
  accessId: string,
  status?: string,
  _id?: string
}
@Component({
  name: 'accessList',
  components: {
    accessTable,
    drawer,
    addOrEdit
  }
})
export default class AccessList extends Vue {
  @Ref() private readonly accessInfo !: addOrEdit
  private $message: any
  private $confirm: any
  private $store: any

  private limitArr: any = [] // 权限

  private tablePages = { // 翻页
    current: 1,
    pageSize: 10,
    total: 0
  }

  private quickSearchForm: any = { // 快捷检索数据（座席状态名称）
    form: {
      name: '', // 座席状态名称
      isEnable: ''
    },
    advSearchOptions: [
      { label: '状态名称', inputType: 'input', placeholder: '请输入状态名称', name: 'name', clearable: true },
      {
        label: '状态',
        name: 'isEnable',
        inputType: 'select',
        clearable: false,
        selectData: [
          { name: '全部', _id: '' },
          { name: '启用', _id: 'open' },
          { name: '停用', _id: 'close' }
        ],
        defaultProp: { label: 'name', value: '_id' }
      }
    ]
  }

  private statusMap = { // 渠道状态
    open: { name: '启用', iconClass: 'green-color V7_iconV7tubiao_dian' },
    close: { name: '停用', iconClass: 'red-color V7_iconV7tubiao_dian' }
  }

  private drawer = { // 详情抽屉
    title: '新增座席状态', // 标题
    isShow: false // 是否展示
  }

  private tableHeader: any = [ // table表头
    { label: '座席状态', prop: 'name', width: 150 },
    { label: '类型', prop: 'typeName' },
    { label: '状态', prop: 'isEnable', isDictionary: true, dictionary: this.statusMap, showStatusIcon: true, width: 70 },
    { label: '最后更新时间', prop: 'lastUpdateTime' },
    { label: '最后操作人', prop: 'lastUpdateUser' }
  ]

  private tableData = [] // table数据

  private confirmFun () { // 保存事件
    this.$nextTick(() => {
      const formRef = this.accessInfo.$refs.accessForm as ElForm
      formRef.validate(valide => {
        if (valide) {
          const sendUrl = '/im-center/action/user/status/config/add'
          const sendData = deepClone(this.accessInfo.agentStatusForm)
          sendData.isEnable = sendData.isEnable === 'open'
          const successMsg = sendData._id ? '编辑座席状态成功' : '添加座席状态成功'
          const actionData = { url: sendUrl, method: 'POST', data: { ...sendData } }
          channelConfigMoudle.channelCommonAction(actionData).then(res => {
            if (res) {
              this.drawer.isShow = false
              this.$message.success(successMsg)
              this.queryTableList(sendData._id === '' ? 'add' : null)
              this.accessInfo.setAgentStatusData()
            }
          })
        }
      })
    })
  }

  private handleState (obj: InterStatus) { // 座席状态切换
    const statusMap = { open: 'open', close: 'close' }
    const status = statusMap[obj.isEnable]
    const statusName = status === 'open' ? '停用' : '启用'
    const sendUrl = '/im-center/action/user/status/config/add'
    const sendData = { url: sendUrl, data: { _id: obj._id, isEnable: status !== 'open', name: obj.name }, method: 'POST' }
    this.$confirm(`确定要${statusName}该座席状态吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      channelConfigMoudle.channelCommonAction(sendData).then(res => {
        if (res) {
          this.$message.success('变更座席状态成功')
          this.queryTableList()
        }
      })
    })
  }

  private queryTableList (addSuccess?: any) { // 查询table数据
    const { name, isEnable } = this.quickSearchForm.form
    const sendData: any = {}
    if (name) {
      sendData.name = name
    }
    if (isEnable) {
      sendData.isEnable = isEnable === 'open'
    }
    const actionData = { url: '/im-center/action/user/status/config/query', method: 'POST', data: { ...sendData } }
    channelConfigMoudle.channelCommonAction(actionData).then(res => {
      if (res.data) {
        const list = res.data || []
        if (list.length > 0) {
          list.forEach((item: any) => {
            item.typeName = item.type === 'system' ? '系统默认' : '自定义'
            item.lastUpdateTime = item.updateTime ? item.updateTime : '--'
            const agentObj = deepClone(CommonModule.publicCache.userListObj)[item.updateUser]
            item.lastUpdateUser = agentObj ? agentObj.name : '--'
            item.isEnable = item.isEnable ? 'open' : 'close'
          })
        }
        this.tableData = res.data
      }
    })
  }

  private addFun () { // 点击新增事件
    this.drawer.isShow = true
    this.$nextTick(() => {
      this.accessInfo.setAgentStatusData() // 新增时需要清空抽屉表单内容
    })
  }

  private cancelFun () { // 抽屉取消事件
    this.drawer.isShow = false
    this.accessInfo.setAgentStatusData() // 取消时需要清空抽屉表单内容
  }

  private editFun (obj: any) { // 编辑座席状态
    this.drawer.isShow = true
    this.drawer.title = '编辑座席状态'
    this.$nextTick(() => {
      this.accessInfo.setAgentStatusData(obj)
    })
  }

  private mounted () {
    let handlers: any = []
    this.limitArr = this.$store.state.common.session.user.functions // 权限处理
    if (checkPermission(null, { value: ['access_list_edit'] })) { // 编辑权限
      handlers.push({ name: '编辑', handleFn: (scope: any) => this.editFun(scope.row) })
    }
    if (checkPermission(null, { value: ['access_list_enableOrDisable'] })) { // 停用启用权限
      handlers = [...handlers,
        ...[
          { name: '停用', className: 'danger', field: 'isEnable', status: 'open', handleFn: (scope: any) => this.handleState(scope.row) },
          { name: '启用', field: 'isEnable', status: 'close', handleFn: (scope: any) => this.handleState(scope.row) }
        ]
      ]
    }
    this.tableHeader.push({ label: '操作', width: 100, handlers })
    this.queryTableList()
  }
}
</script>
<style lang="stylus">
 .accessList
  height 100%
</style>
